/*
 * @Author: 脉迈
 * @Date: 2022-01-11 17:14:03
 * @LastEditors: 脉迈
 * @LastEditTime: 2022-01-18 14:28:23
 */
const Path = require('path')
const fs = require('fs')
const Router = require("@koa/router");

//自动扫指定目录下面的文件并且加载
const scanFilesByFolder = function (dir, cb) {
	let _folder = Path.resolve(__dirname, dir);
	
  // 判断传入的目录是否存在
	if(!getFileStat(_folder)){
		console.log('111')
		return;
	}
	try {
    // 读取目录的内容
		const files = fs.readdirSync(_folder);
		files.forEach((file) => {
			let filename = file.replace('.js', '');
			let fileModule = require(_folder + '/' + filename);
			cb && cb(filename, fileModule);
		})

	} catch (error) {
		console.log('文件自动加载失败...', error);
	}
}
// 检测文件夹是否存在
/**
 * @param {string} path 路径
 */
const getFileStat = function(path) {
	try {
		fs.statSync(path);
		return true;
	} catch (err) {
		return false;
	}
}
// 配置信息
const initConfig = function(){
	let config = {};
	scanFilesByFolder('../config',(filename, content)=>{
		config = {...config, ...content};
	});
	return config;
}

// 初始化路由
const initRouter = function(app){
	const router = new Router();

	require('../router/index')({...app, router});
	
	return router;
}

// 初始化控制器
const initController = (app)=>{
	let controllers = {}
  scanFilesByFolder('../controller', (filename, controller)=>{
		
    controllers[filename] = controller(app);
	})
  return controllers;
}

// 初始化扩展
const initExtend = (app)=> {
	scanFilesByFolder('../extend',(filename, extendFn)=>{
		app['$' + filename] = Object.assign(app['$' + filename] || {}, extendFn(app))
	})
}

// 初始化中间件
const initMiddleware = (app)=>{
	let middlewares = {}
	scanFilesByFolder('../middleware',(filename,middleware)=>{
		middlewares[filename] = middleware(app);
	})
	//初始化配置中间件
	if(app.$config.middleware && Array.isArray(app.$config.middleware)){
		app.$config.middleware.forEach(mid=>{
			if(middlewares[mid]){
				app.$app.use(middlewares[mid]);
			}
		})
	}
	return middlewares;
}

// 初始Modles

const initModels = () => {
	let models = {}
	scanFilesByFolder('../models', (filename, model)=>{
		models[filename] = model
	})
	return models;
}


module.exports = {
	initConfig,
	initController,
	initRouter,
	initExtend,
	initMiddleware,
	initModels
}